from urllib.request import Request,urlopen
from urllib.parse import quote,urlencode

#拼接地址
def get_url(word):
    ur1 = 'https://www.baidu.com/s?{}'
    params = urlencode({'wd':word})
    ur1 = ur1.format(params)
    return ur1

#发送请求，保存本地文件
def request_url(ur1,filename):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
    }
    req = Request(ur1,headers=headers)
    res = urlopen(req)
    html = res.read().decode('utf-8')
    with open(filename,'w',encoding='utf-8') as f:
        f.write(html)

if __name__=='__main__':
    word = input("请输入搜索内容")
    ur1 = get_url(word)
    filename = word + '.html'
    request_url(ur1,filename)





